package com.ie.service.before;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.common.http.ResponseResult;
import com.ie.entity.admin.CartEntity;
import com.ie.entity.admin.GoodsEntity;
import com.ie.mapper.before.CartMapper;
import com.ie.service.admin.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, CartEntity> implements CartService {
    @Autowired
    private GoodsService goodsService; // 注入商品服务，用于查询商品详情

    @Override
    public ResponseResult<Map<String, Object>> addCart(CartEntity cartEntity) {
        Long goodsNum = lambdaQuery().eq(CartEntity::getBusertableId, cartEntity.getBusertableId())
                .eq(CartEntity::getGoodstableId, cartEntity.getGoodstableId()).count();
        boolean result = false;
        if (goodsNum > 0) {
            //更新购物车数量
            LambdaUpdateWrapper<CartEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(CartEntity::getShoppingnum, cartEntity.getShoppingnum() + 1)
                    .eq(CartEntity::getBusertableId, cartEntity.getBusertableId())
                    .eq(CartEntity::getGoodstableId, cartEntity.getGoodstableId());
            result = update(updateWrapper);
        } else {//添加新商品到购物车
            result = save(cartEntity);
        }
        if (result) {
            return ResponseResult.getMessageResult(null, "A001");
        } else {
            return ResponseResult.getMessageResult(null, "A002");
        }
    }

    @Override
    @Transactional
    public ResponseResult<Map<String, Object>> bupDateCart(CartEntity cartEntity) {

        List<Integer> bcid = cartEntity.getBcid();
        List<Integer> bshoppingnum = cartEntity.getBshoppingnum();
        ArrayList<CartEntity> cartEntities = new ArrayList<CartEntity>();
        for (int i = 0; i < bcid.size(); i++) {
            CartEntity cartEntity1 = new CartEntity();
            cartEntity1.setId(bcid.get(i));
            cartEntity1.setShoppingnum(bshoppingnum.get(i));
            cartEntities.add(cartEntity1);
        }
        boolean b = updateBatchById(cartEntities);
        if (b) {
            return ResponseResult.getMessageResult(null, "A001");
        } else {
            return ResponseResult.getMessageResult(null, "A002");
        }
    }

    @Override
    public ResponseResult<Map<String, Object>> clearCart(CartEntity cartEntity) {
        if (cartEntity == null || cartEntity.getBusertableId() == null) {
            return ResponseResult.error("参数不能为空");
        }

        QueryWrapper<CartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("busertable_id", cartEntity.getBusertableId());
        boolean result = remove(queryWrapper);

        return result ?
                ResponseResult.getMessageResult(null, "A001") :
                ResponseResult.getMessageResult(null, "A002");
    }


    @Override
    public ResponseResult<Map<String, Object>> getCartList(Integer busertableId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> cartGoodsList = new ArrayList<>();

        if (busertableId == null) {
            resultMap.put("cartList", new ArrayList<>());
            resultMap.put("totalPrice", BigDecimal.ZERO);
            return ResponseResult.success(resultMap, "用户ID不能为空");
        }

        QueryWrapper<CartEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("busertable_id", busertableId);
        List<CartEntity> cartEntities = list(queryWrapper);

        if (cartEntities.isEmpty()) {
            resultMap.put("cartList", new ArrayList<>());
            resultMap.put("totalPrice", BigDecimal.ZERO);
            return ResponseResult.success(resultMap, "购物车数据获取成功");
        }

        for (CartEntity cartEntity : cartEntities) {
            Map<String, Object> goodsMap = new HashMap<>();
            GoodsEntity goods = goodsService.getById(cartEntity.getGoodstableId());
            if (goods != null) {
                goodsMap.put("goodsId", goods.getId());
                goodsMap.put("goodsName", goods.getGname());
                goodsMap.put("price", goods.getGrprice());
                goodsMap.put("quantity", cartEntity.getShoppingnum());
                goodsMap.put("imageUrl", goods.getGpicture());
            }
            cartGoodsList.add(goodsMap);
        }

        BigDecimal totalPrice = cartGoodsList.stream()
                .filter(item -> item.get("price") != null && item.get("quantity") != null)
                .map(item -> {
                    Double price = (Double) item.get("price");
                    Integer quantity = (Integer) item.get("quantity");
                    return new BigDecimal(price).multiply(new BigDecimal(quantity));
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        resultMap.put("cartList", cartGoodsList);
        resultMap.put("totalPrice", totalPrice);
        return ResponseResult.success(resultMap, "购物车数据获取成功");
    }

    // 在 CartServiceImpl 类中添加这个方法（如果没有的话）
    @Override
    public ResponseResult<Map<String, Object>> removeCart(Integer id) {
        boolean result = removeById(id);
        if (result) {
            return ResponseResult.getMessageResult(null, "A001"); // 删除成功
        } else {
            return ResponseResult.getMessageResult(null, "A002"); // 删除失败
        }
    }

    @Override
    public ResponseResult<Map<String, Object>> getCartListByBusertableId(String busertableId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> cartGoodsList = new ArrayList<>();

        if (busertableId == null || busertableId.isEmpty()) {
            resultMap.put("cartList", new ArrayList<>());
            resultMap.put("totalPrice", BigDecimal.ZERO);
            return ResponseResult.success(resultMap, "用户ID不能为空");
        }

        try {
            Integer id = Integer.parseInt(busertableId);
            List<CartEntity> cartEntities = baseMapper.selectByBusertableId(id);

            if (cartEntities.isEmpty()) {
                resultMap.put("cartList", new ArrayList<>());
                resultMap.put("totalPrice", BigDecimal.ZERO);
                return ResponseResult.success(resultMap, "购物车数据获取成功");
            }

            for (CartEntity cartEntity : cartEntities) {
                Map<String, Object> goodsMap = new HashMap<>();
                GoodsEntity goods = goodsService.getById(cartEntity.getGoodstableId());
                if (goods != null) {
                    goodsMap.put("goodsId", goods.getId());
                    goodsMap.put("goodsName", goods.getGname());
                    goodsMap.put("price", goods.getGrprice());
                    goodsMap.put("quantity", cartEntity.getShoppingnum());
                    goodsMap.put("imageUrl", goods.getGpicture());
                }
                cartGoodsList.add(goodsMap);
            }

            BigDecimal totalPrice = cartGoodsList.stream()
                    .filter(item -> item.get("price") != null && item.get("quantity") != null)
                    .map(item -> {
                        Double price = (Double) item.get("price");
                        Integer quantity = (Integer) item.get("quantity");
                        return new BigDecimal(price).multiply(new BigDecimal(quantity));
                    })
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            resultMap.put("cartList", cartGoodsList);
            resultMap.put("totalPrice", totalPrice);
            return ResponseResult.success(resultMap, "购物车数据获取成功");
        } catch (NumberFormatException e) {
            resultMap.put("cartList", new ArrayList<>());
            resultMap.put("totalPrice", BigDecimal.ZERO);
            return ResponseResult.success(resultMap, "用户ID必须是数字");
        }
    }
}